﻿#region Using namespaces

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Windows;

#endregion

namespace BOL.Apps.GeneNetworkBrowser.Analysis
{
    public sealed class WorkItemQueue<I, O> : Queue<WorkItem<I, O>>, INotifyCollectionChanged
    {
        #region Constructor

        public WorkItemQueue(int numWorkers,
                         Action<BackgroundWorker, DoWorkEventArgs> doWork,
                         Action<BackgroundWorker, ProgressChangedEventArgs> progressChanged = null,
                         Action<BackgroundWorker, RunWorkerCompletedEventArgs> runWorkCompleted = null)
            : base(numWorkers)
        {
            this._workers = new BackgroundWorker[numWorkers];

            int i = 0;
            while (i < _workers.Length)
            {
                _workers[i] = new BackgroundWorker();
                _workers[i].WorkerReportsProgress = true;
                _workers[i].WorkerSupportsCancellation = true;

                _workers[i].DoWork += (s, args) =>
                {
                    doWork((BackgroundWorker)s, args);
                };

                _workers[i].ProgressChanged += (s, args) =>
                {
                    // Call progressChanged if its not null
                    if (progressChanged != null) 
                        progressChanged((BackgroundWorker)s, args);
                };
                _workers[i].RunWorkerCompleted += (s, args) =>
                {
                    // Call runWorkCompleted if its not null
                    if (runWorkCompleted != null) 
                        runWorkCompleted((BackgroundWorker)s, args);

                    DoNext();
                };
                i++;
            }
        }

        #endregion
    }
}
